package com.tedu.springboot2206.controller;

import com.tedu.springboot2206.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    //表示保存所有用户信息的目录users
    private static File userDir;
    static {
        userDir = new File("./users");
        if (!userDir.exists()){
            userDir.mkdirs();
        }
    }
    @RequestMapping("/deleteUser")
    public void delete(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理删除用户!!!!!!!!!!!!!!!!!!!!!!!");
        //http://localhost:8080/deleteUser?username=fancq
        String username = request.getParameter("username");
        System.out.println("要删除的用户是:"+username);
        File file = new File(userDir,username+".obj");
        file.delete();
        try {
            response.sendRedirect("/userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/userList")
    public void userList(HttpServletRequest request,HttpServletResponse response){
        System.out.println("开始处理动态页面");

        List<User> userList = new ArrayList<>();
        File[] subs = userDir.listFiles(f->f.getName().endsWith(".obj"));
        for (File file:subs){
            try (FileInputStream fis = new FileInputStream(file);
                 ObjectInputStream ois = new ObjectInputStream(fis);
            ){
                User user = (User)ois.readObject();
                userList.add(user);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }
        System.out.println(userList);
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border=\"1\">");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("<td>操作</td>");

            pw.println("</tr>");
            for (User user:userList){
                pw.println("<tr>");
                pw.println("<td>"+user.getUsername()+"</td>");
                pw.println("<td>"+user.getPassword()+"</td>");
                pw.println("<td>"+user.getNickname()+"</td>");
                pw.println("<td>"+user.getAge()+"</td>");
                pw.println("<td><a href='/deleteUser?username="+user.getUsername()+"'>删除</a></td>");
                pw.println("</tr>");
            }

            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request,HttpServletResponse response){
        //1
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+","+password);

        //2

        if (username==null||username.isEmpty()||password==null||password.isEmpty()){
            try {
                response.sendRedirect("/login_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        File file = new File(userDir,username+".obj");
        if(file.exists()){ //文件说明该用户是否存在
            try {
                FileInputStream fis = new FileInputStream(file);
                ObjectInputStream ois = new ObjectInputStream(fis);

                User user = (User)ois.readObject();

                if (user.getPassword().equals(password))
                {
                    response.sendRedirect("/login_success.html");
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        }
        try {
            response.sendRedirect("/login_fail.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("registerUser")
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理注册");

        //1获取注册页面上的表单信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);

        if (username==null||username.isEmpty()||password==null||password.isEmpty()
            ||nickname==null||nickname.isEmpty()||ageStr==null||ageStr.isEmpty()||
            !ageStr.matches("[0-9]+")){
            try {
                response.sendRedirect("/reg_info_error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        int age = Integer.parseInt(ageStr); //将年龄转换为int值

        //2将该注册用户信息一User对象形式表示并序列化到文件中保存
        User user = new User(username,password,nickname,age);

        File file = new File(userDir,username+".obj");

        if (file.exists()){
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try(
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            ) {
            oos.writeObject(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3让浏览器重定向到指定的路径查看处理结果页面
        try {
            response.sendRedirect("reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    3.1:通过request获取表单提交的用户名和密码
//    3.2:读取users目录下对应的用户文件(反序列化)
//    3.3:比对用户密码
//    3.4:响应用户登录成功或失败页面
//    登录成功的标准:用户名和密码都输入正确
//    登录失败的标准:用户名错误或密码错误

}
